package com.xzbd.sunnn.service.user;

import com.xzbd.sunnn.model.user.User;
import com.xzbd.sunnn.repository.user.UserRepository;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * sun 2017-11-11
 */
public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;


    @Override
    public User findOne(User user) {
        Assert.notNull(user,"参数 user 不能为 null");
        return userRepository.findOne(new Specification<User>() {
            //创建条件
            List<Predicate> predicates = new ArrayList<>();
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder builder) {

                if(Objects.nonNull(user.getNumber())) predicates.add(builder.equal(root.get("number").as(Integer.class),user.getNumber()));
                if(Objects.nonNull(user.getAge())) predicates.add(builder.ge(root.get("age"),user.getAge()));
                return builder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        });
    }
}
